package cn.easy.mortgage.web;

import cn.easy.base.bean.PageBean;
import cn.easy.base.bean.common.AjaxResultBean;
import cn.easy.base.domain.Area;
import cn.easy.base.domain.User;
import cn.easy.base.service.AreaService;
import cn.easy.base.utils.BaseUtils;
import cn.easy.base.utils.Global;
import cn.easy.base.web.BaseController;
import cn.easy.mortgage.domain.Channel;
import cn.easy.mortgage.domain.EstateEvalInfo;
import cn.easy.mortgage.domain.LoanRequest;
import cn.easy.mortgage.service.ChannelService;
import cn.easy.mortgage.service.LoanRequestService;
import cn.easy.mortgage.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author huangm
 */
@Controller
@RequestMapping("/loanRequest")
public class LoanRequestController extends BaseController {
    @Autowired
    private LoanRequestService	loanRequestService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private AreaService areaService;

    @RequestMapping("")
    String index(Model model, HttpServletRequest request) {
        if (hasPermission(Constants.REQUEST_SEARCH_GLOBAL) || getChannelPid(getCurrentUserId()).equals(Constants.CHANNEL_PARENT)){
            model.addAttribute("isParent", true);
        }
        if (hasPermission(Constants.REQUEST_SEARCH_GLOBAL)){
            model.addAttribute("isGlobal", true);
        }
        model.addAttribute("currentUserId", getCurrentUserId());
        return "loanRequest/index";
    }

    @RequestMapping("/list")
    @ResponseBody
    Page<LoanRequest> list(PageBean pageBean, HttpServletRequest request) {
        Map<String, Object> searchParams = searchParams(request);
        searchParams.put("EQ_status", Constants.REQUEST_STATUS_SUBMIT);
        Page<LoanRequest> page = loanRequestService.search(searchParams, pageBean);
        return fieldValues(page);
    }

    @RequestMapping("/potential")
    String potential(Model model, HttpServletRequest request) {
        if (hasPermission(Constants.REQUEST_SEARCH_GLOBAL) || getChannelPid(getCurrentUserId()).equals(Constants.CHANNEL_PARENT)) {
            model.addAttribute("isParent", true);
        }
        if (hasPermission(Constants.REQUEST_SEARCH_GLOBAL)){
            model.addAttribute("isGlobal", true);
        }
        model.addAttribute("currentUserId", getCurrentUserId());
        return "loanRequest/potential";
    }

    @RequestMapping("/potential/list")
    @ResponseBody
    Page<LoanRequest> potentialList(PageBean pageBean, HttpServletRequest request) {
        Map<String, Object> searchParams = searchParams(request);
        searchParams.put("EQ_status", Constants.REQUEST_STATUS_WAIT);
        Page<LoanRequest> page = loanRequestService.search(searchParams, pageBean);
        return fieldValues(page);
    }

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    String formGet(@RequestParam(value = "id", required = false) String id, Model model, HttpServletRequest request) {
        if (isValidId(id)) {
            LoanRequest loanRequest = loanRequestService.getOne(id);
            model.addAttribute("loanRequest", loanRequest);
        } else {
            model.addAttribute("loanRequest", new LoanRequest());
        }
        return "loanRequest/form";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    @ResponseBody
    AjaxResultBean formPost(LoanRequest loanRequest, HttpServletRequest request) {
        if (!loanRequest.getManagerId().equals(getCurrentUserId()) && !hasPermission(Constants.REQUEST_SEARCH_GLOBAL)) {
            return toError("您不是负责人，无法提交意向");
        }
        if (Constants.REQUEST_STATUS_WAIT.equals(loanRequest.getStatus())){
            loanRequest.setStatus(Constants.REQUEST_STATUS_SUBMIT);
        }
        loanRequestService.save(loanRequest);
        return toSuccess("提交成功");
    }

    @RequestMapping("/delete")
    @ResponseBody
    AjaxResultBean delete(@RequestParam(value = "id") String id) {
        loanRequestService.delete(id);
        return toSuccess("删除成功");
    }

    @RequestMapping("/view")
    String view(@RequestParam(value = "id") String id, Model model) {
        LoanRequest loanRequest = loanRequestService.getOne(id);
        Channel channel = channelService.getOne(loanRequest.getChannelId());
        model.addAttribute("area", areaService.getName(loanRequest.getArea()));
        model.addAttribute("loanRequest", loanRequest);
        model.addAttribute("channelName", channel != null ? channel.getName() : "");
        EstateEvalInfo estateEvalInfo = loanRequest.getEstateEvalInfo();
        model.addAttribute("estateEvalInfo", estateEvalInfo);
        return "loanRequest/view";
    }

    @RequestMapping("/allocation")
    @ResponseBody
    AjaxResultBean allocation(@RequestParam(value = "ids") String[] ids, @RequestParam(value = "userId") String userId) {
        if (hasPermission(Constants.REQUEST_SEARCH_GLOBAL) || getChannelPid(getCurrentUserId()).equals(Constants.CHANNEL_PARENT)) {
            List<LoanRequest> loanRequestList = loanRequestService.findAll(Arrays.asList(ids));
            for (LoanRequest loanRequest : loanRequestList) {
                if (Constants.REQUEST_STATUS_SUBMIT.equals(loanRequest.getStatus())) {
                    loanRequest.setTelSaleManager(userId);
                }
                if (Constants.REQUEST_STATUS_WAIT.equals(loanRequest.getStatus())) {
                    loanRequest.setManagerId(userId);
                }
                loanRequestService.save(loanRequest);
            }
            return toSuccess("设置成功");
        } else {
            return toError("您没有权限分配");
        }
    }

    @RequestMapping("/select")
    String select(Integer type, Model model, @RequestParam(value = "isMultiSelect", required = false) boolean isMultiSelect) {
        model.addAttribute("isMultiSelect", isMultiSelect);
        Channel channel = getChannel(getCurrentUserId());
        if (!hasPermission(Constants.REQUEST_SEARCH_GLOBAL)) {
            model.addAttribute("currentChannelNo", channel.getNo());
        } else {
            model.addAttribute("currentChannelNo", Constants.CHANNEL_DEFAULT_GLOBAL);
        }
        return "loanRequest/select";
    }

    @RequestMapping("/user/list")
    @ResponseBody
    Map userList(PageBean pageBean, HttpServletRequest request) {
        List<Channel> userList = channelService.search(searchParams(request), new Sort(Sort.Direction.DESC, "createdAt"));
        return toGridMap(userList);
    }

    @RequestMapping("/export/potential")
    void exportPotential(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PageBean pageBean = new PageBean();
        Map<String, Object> searchParams = searchParams(request);
        searchParams.put("EQ_status", Constants.REQUEST_STATUS_WAIT);
        Page<LoanRequest> page = loanRequestService.search(searchParams, pageBean);

        String title = "潜在客户表";
        String[] colNames = new String[0];
        colNames = new String[]{
                "物业类型", "产权地址", "建筑面积", "住房总价", "负责人", "来源", "渠道", "手机号", "地区", "创建时间", "更新时间"
        };
        String[][] content = new String[(int) page.getTotalElements()][colNames.length];
        int i = 0;
        while (page.getNumberOfElements() > 0) {
            Page<LoanRequest> loanRequestPage = fieldValues(page);
            for (Object bean : loanRequestPage.getContent()) {
                Map<String, Object> map = (Map) bean;
                String[] oneContentArray = new String[]{
                        BaseUtils.getMapStrVal(map, "config_estateEval_propertyType"),
                        BaseUtils.getMapStrVal(map, "estateEval_houseAddress"),
                        BaseUtils.getMapStrVal(map, "estateEval_roomSize"),
                        BaseUtils.getMapStrVal(map, "estateEval_houseTotalPrice"),
                        BaseUtils.getMapStrVal(map, "manager_realname"),
                        BaseUtils.getMapStrVal(map, "channel_name"),
                        BaseUtils.getMapStrVal(map, "channelNo_name"),
                        BaseUtils.getMapStrVal(map, "mobile"),
                        BaseUtils.getMapStrVal(map, "area_name"),
                        BaseUtils.getMapStrVal(map, "createdAt"),
                        BaseUtils.getMapStrVal(map, "updatedAt")
                };
                content[i++] = oneContentArray;
            }
            pageBean.setCurrentPage(pageBean.getCurrentPage() + 1);
            page = loanRequestService.search(searchParams, pageBean);
        }


        toExportExcel(title, colNames, content, request, response);
    }

    @RequestMapping("/export/intention")
    void exportIntention(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PageBean pageBean = new PageBean();
        Map<String, Object> searchParams = searchParams(request);
        searchParams.put("EQ_status", Constants.REQUEST_STATUS_SUBMIT);
        Page<LoanRequest> page = loanRequestService.search(searchParams, pageBean);

        String title = "意向客户表";
        String[] colNames = new String[0];
        colNames = new String[]{
                "物业类型", "产权地址", "建筑面积", "住房总价", "负责人", "电销经理 ", "来源", "贷款金额(万)", "来源", "渠道", "姓名",
                "手机号", "房产购入时间", "产权共有人", "是否唯一住房", "当前抵押状态", "住房使用状态", "婚姻状态", "2年内是否逾期",
                "逾期次数", "资金用途", "创建时间", "更新时间"
        };

        String[][] content = new String[(int) page.getTotalElements()][colNames.length];
        int i = 0;
        while (page.getNumberOfElements() > 0) {
            Page<LoanRequest> loanRequestPage = fieldValues(page);
            for (Object bean : loanRequestPage.getContent()) {
                Map<String, Object> map = (Map) bean;
                String[] oneContentArray = new String[]{
                        BaseUtils.getMapStrVal(map, "config_estateEval_propertyType"),
                        BaseUtils.getMapStrVal(map, "estateEval_houseAddress"),
                        BaseUtils.getMapStrVal(map, "estateEval_roomSize"),
                        BaseUtils.getMapStrVal(map, "estateEval_houseTotalPrice"),
                        BaseUtils.getMapStrVal(map, "manager_realname"),
                        BaseUtils.getMapStrVal(map, "telSaleManager_realname"),
                        BaseUtils.getMapStrVal(map, "loanAmount"),
                        BaseUtils.getMapStrVal(map, "channel_name"),
                        BaseUtils.getMapStrVal(map, "channelNo_name"),
                        BaseUtils.getMapStrVal(map, "name"),
                        BaseUtils.getMapStrVal(map, "mobile"),
                        BaseUtils.getMapStrVal(map, "area_name"),
                        BaseUtils.getMapStrVal(map, "boughtAt"),
                        BaseUtils.getMapStrVal(map, "config_propertyCoOwner"),
                        BaseUtils.getMapStrVal(map, "config_isOnlyHouse"),
                        BaseUtils.getMapStrVal(map, "config_mortgageStatus"),
                        BaseUtils.getMapStrVal(map, "config_useStatus"),
                        BaseUtils.getMapStrVal(map, "config_maritalStatus"),
                        BaseUtils.getMapStrVal(map, "config_isOverdue"),
                        BaseUtils.getMapStrVal(map, "overdueCount"),
                        BaseUtils.getMapStrVal(map, "fundUse"),
                        BaseUtils.getMapStrVal(map, "createdAt"),
                        BaseUtils.getMapStrVal(map, "updatedAt")
                };
                content[i++] = oneContentArray;
            }
            pageBean.setCurrentPage(pageBean.getCurrentPage() + 1);
            page = loanRequestService.search(searchParams, pageBean);
        }
        toExportExcel(title, colNames, content, request, response);
    }

    private Page<LoanRequest> fieldValues(Page<LoanRequest> page) {
        setConfigFieldValues(page, Constants.REQUEST_STATUS_KEY, "status");
        setFieldValues(page, Channel.class, "channelId", new String[]{"name"});
        setFieldValues(page, Channel.class, "channelNo", "no", new String[]{"name"});
        setFieldValues(page, EstateEvalInfo.class, "estateEvalId", new String[]{"houseAddress", "propertyType", "roomSize", "houseTotalPrice"});
        setConfigFieldValues(page, Constants.PROPERTY_TYPE_KEY, "estateEval_propertyType");
        setFieldValues(page, Area.class, "area", "code", new String[]{"name"});
        setFieldValues(page, User.class, "managerId", new String[]{"realname"});
        setFieldValues(page, User.class, "telSaleManager", new String[]{"realname"});
        setConfigFieldValues(page, Constants.HAVE_OR_NOT_KEY, "propertyCoOwner");
        setConfigFieldValues(page, Global.IF_OR_NOT_ENUM_KEY, "isOnlyHouse");
        setConfigFieldValues(page, Constants.HAVE_OR_NOT_KEY, "mortgageStatus");
        setConfigFieldValues(page, Constants.HOUSE_USE_STATUS_KEY, "useStatus");
        setConfigFieldValues(page, Constants.MARITAL_STATUS_KEY, "maritalStatus");
        setConfigFieldValues(page, Constants.HAVE_OR_NOT_KEY, "isOverdue");
        return page;
    }

    private Channel getChannel(String userId) {
        if (userId == null || StringUtils.isBlank(userId)) {
            return null;
        }
        Channel channel = channelService.findByUserId(userId);
        return channel;
    }

    private String getChannelPid(String userId) {
        Channel channel = getChannel(userId);
        return channel == null ? null : channel.getPid();
    }
}


